package com.lanxin.handler;

import com.lanxin.enums.HttpStatusEnum;
import com.lanxin.result.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author cyh
 * @create 2025-09-18 8:19
 */
@RestControllerAdvice
@Slf4j
public class GlobalDefaultExceptionHandler {

    // 捕获参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<Object> handleValidationException(MethodArgumentNotValidException ex) {

        Map<String, String> errors = ex.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(
                        FieldError::getField,
                        FieldError::getDefaultMessage,
                        (msg1, msg2) -> msg1 + "; " + msg2
                ));
        return ResponseResult.fail(400, "参数校验失败", errors);
    }

    // 捕获参数校验异常
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseResult<Object> handleConstraintViolation(ConstraintViolationException ex) {
        Map<String, String> errors = ex.getConstraintViolations().stream()
                .collect(Collectors.toMap(
                        violation -> violation.getPropertyPath().toString(),
                        ConstraintViolation::getMessage,
                        (msg1, msg2) -> msg1 + "; " + msg2
                ));
        return ResponseResult.fail(400, "参数校验失败", errors);
    }

    // 捕获特定异常，例如自定义异常
    @ExceptionHandler(value = BaseException.class)
    public ResponseResult<String> handleCustomException(BaseException e, HttpServletRequest request) {
        String uri = request.getRequestURI();
        log.warn("业务异常 => URI: {}, 错误码: {}, 消息: {}", uri, e.getCode(), e.getMessage());
        return ResponseResult.fail(e.getCode(), e.getMessage());
    }

    // 捕获所有异常
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult<String> handleException(Exception e, HttpServletRequest request) {

        String uri = request.getRequestURI();
        log.error("系统异常 => URI: {}, 错误信息: {}", uri, e.getMessage(), e);
        return ResponseResult.fail(HttpStatusEnum.ERROR.getCode(),e.getMessage());
    }


}
